<?php defined('SYSPATH') or die('No direct script access.');
  
class Controller_Cms_Admin extends Controller_Cms_Setbackend
{
	private $model;
	
	public function before(){
		parent::before();
		$this->model = new Model_Cms_Admin;
    }
	
	public function action_start()
	{
		$view = View::factory('cms/startadmin');
		$this->template->breadcrumb = html::anchor('admin','Start');
		$this->template->content = $view;
	}
	
	public function action_settings()
	{
		if($_POST)
		{
			$this->model->save_settings();
			Session::instance()->set('flash_panel','<div class="flash-ok">Dane zostały zmienione</div>');
		}
		$view = View::factory('cms/settings');
		$settings = $this->model->get_settings();
		$view->settings = $settings;
		//echo Kohana::debug($settings);exit;
		$this->template->breadcrumb = html::anchor('admin','Start')." > Ustawienia";
		$this->template->content = $view;
	}
	
	public function action_search()
	{
		$key = trim(Security::xss_clean($_GET['key']));
		$res_ids = array();
		// wyszukiwanie w tablicy videos
		$pages = DB::Select()->from('videos');
		$pages->where('name','like','%'.$key.'%');
		$pages->or_where('text_stripped','like','%'.$key.'%');
		$pages->and_where('published','=',1);
		$res_video = $pages->execute();
		
		$i=0;
		foreach($res_video as $rv)
		{
			$res_ids[$i]['id'] = $rv['id'];
			$res_ids[$i]['type'] = 'video';
			// pobieranie id kolejki
			$film = $this->model->pobierz_film($rv['id']);
			$res_ids[$i]['link'] = 'dodajfilm/'.$film['kolejka_id'].'/'.$rv['id'];
			$res_ids[$i]['title'] = $rv['name'];
			$i++;
		}
		
		// wyszukiwanie w tablicy pages
		$pages = DB::Select()->from('pages');
		$pages->where('title','like','%'.$key.'%');
		$pages->or_where('content_stripped','like','%'.$key.'%');
		$pages->or_where('short_stripped','like','%'.$key.'%');
		$pages->and_where('published','=',1);
		$res_pages = $pages->execute();
		
		foreach($res_pages as $rp)
		{
			if($rp['category'] == 0)
			{
				$res_ids[$i]['id'] = $rp['id'];
				$res_ids[$i]['title'] = $rp['title'];
				$res_ids[$i]['link'] = 'admin/addpage/'.$rp['id'];
				if($rp['category_id'] == 2)
				{
					$res_ids[$i]['type'] = 'aktualnosc';
				}
				else if ($rp['category_id'] == 4)
				{
					$res_ids[$i]['type'] = 'analiza';
				}
				else{
					$res_ids[$i]['type'] = '';
				}
				$i++;
			}
		}
		//echo Kohana::debug($res_ids);exit;
		$view = View::factory('cms/backend_search_results');
		$view->results = $res_ids;
		// liczba rezultatow + odpowedni przypadek rzeczownika 'rezultat'
		$count = count($res_ids);
		if($count == 1) $view->found = '<strong'.$count.'</strong> rezultat';
		else if($count > 1 && $count < 5) $view->found = '<strong>'.$count.'</strong> rezultaty';
		else if($count > 4) $view->found = '<strong>'.$count.'</strong> rezultat�w';
		$this->template->content = $view;
	}
}